package com.lly.pro.controller;

import com.lly.pro.Model.Info;
import com.lly.pro.common.*;
import com.lly.pro.entity.Admin;
import com.lly.pro.entity.HR;
import com.lly.pro.entity.User;
import com.lly.pro.service.AdminService;
import com.lly.pro.service.HRService;
import com.lly.pro.service.UserService;
import com.xiaoleilu.hutool.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author Hommond
 * @date 2/25/2019
 */
@Controller
public class AdminController {
    private Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private AdminService adminService;
    @Autowired
    private HRService hrService;
    @Autowired
    private UserService userService;

    @PostMapping(value = "/admin/info")
    @ResponseBody
    public ResponseJson getInfo(@RequestBody JSONObject param, HttpServletRequest request){
        //获取userId
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");

        //获取当前admin信息
        Admin admin = adminService.findByUserId(userId);

        //将admin的信息付给Info类，过滤掉密码，然后返回
        Info result = new Info();
        result.setAddress(admin.getAddress());
        result.setBirthday(admin.getBirthday());
        result.setDepartment(admin.getDepartment());
        result.setEmail(admin.getEmail());
        result.setAddress(admin.getAddress());
        result.setLevel(admin.getLevel());
        result.setPicture(admin.getPicture());
        result.setQuarters(admin.getQuarters());
        result.setUserId(admin.getUserId());
        result.setUserName(admin.getUserName());
        return ResponseJsonUtil.getSuccessResult(result);
    }
    /**
     * 修改密码
     * @Param param
     * @Param request
     * @return
     */
    @PostMapping(value = "/admin/changePassword")
    @ResponseBody
    public ResponseJson changePassword(@RequestBody JSONObject param,HttpServletRequest request){
        //检查是否只有newPassword参数
        if (!ParamterCheckUtil.isChangePasswordParamComplete(param)){
            return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.MISSING_PARAMETERS,"缺少newPassword参数");
        }
        //获取newPassword
        String newPassword = param.getStr("newPassword");
        //获取userId
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");
        //更改密码为newPassword
        Admin admin = adminService.findByUserId(userId);
        admin.setPassword(newPassword);
        return adminService.adminChange(admin);
    }
    /**
     * 修改信息
     * @Param param
     * @Param request
     * @return
     */
    @PostMapping(value = "/admin/changeInfo")
    @ResponseBody
    public ResponseJson changeInfo(@RequestBody JSONObject param,HttpServletRequest request){
        HttpSession session = request.getSession();
        Long userId = (Long) session.getAttribute("userId");

        //获取目标admin的信息
        Admin admin = adminService.findByUserId(userId);

        //利用java反射机制将param中数据赋值到admin里
        for (String fieldName : param.keySet()){
            if (!Tools.setFieldValueByFieldName(fieldName,admin,param.getObj(fieldName))){
                return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.NOT_LOGGED_IN,"参数"+fieldName+"有误！！！");
            }
        }
        return adminService.adminChange(admin);
    }

    /**
     * 按部门查询
     * @Param param
     * @return
     */
    @PostMapping(value = "/admin/hr/department")
    @ResponseBody
    public ResponseJson getHRByDepartment(@RequestBody JSONObject param){

        String department = param.getStr("department");
        if( StringUtils.isEmpty(department)){
            return ResponseJsonUtil.getSuccessResult(hrService.findAll());
        }
        else{
            return ResponseJsonUtil.getSuccessResult(hrService.findByDepartment(department));
        }
    }

    /**
     * 联合查询，目前只适合精准查询
     * @Param param
     * @Param request
     * @return
     */
    @PostMapping(value = "/admin/hr/select")
    @ResponseBody
    public ResponseJson getHRBySelect(@RequestBody JSONObject param){

        if (!ParamterCheckUtil.isContainTargetParams(HR.class,param)){
            return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.MISSING_PARAMETERS,"参数错误！");
        }

        return ResponseJsonUtil.getSuccessResult(hrService.unionQuery(param));
    }

    /**
     * 新增用户
     * @return
     */
    @PostMapping(value = "/admin/add")
    @ResponseBody
    public ResponseJson addNewUser(@RequestBody JSONObject param){

        String identity = param.getStr("identity");

        if (StringUtils.isBlank(identity) || !ParamterCheckUtil.isLoginParamComplete(param)){
            return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.MISSING_PARAMETERS,"缺少参数");
        }
        else{
            return addOneUser(param,identity);
        }
    }
    /**
     * 新增一个用户
     * @return
     */
    private ResponseJson addOneUser(JSONObject param,String identity){
        if (StringUtils.equals(identity,Identity.EMPLOYEE)){
            User user = new User();

            try{
                userService.save(user);
            }catch (Exception e){
                logger.info("新建employee错误,请检查参数"+param.toString());
                return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.ADD_USER_ERROR,"新建用户失败，请检查参数是否有误！");
            }
            return ResponseJsonUtil.SUCCESS_WITH_NO_DATA;

        }else if(StringUtils.equals(identity,Identity.HR)){
            HR user = new HR();

            try{
                hrService.save(user);
            }catch (Exception e){
                logger.info("新建hr错误,请检查参数"+param.toString());
                return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.ADD_USER_ERROR,"新建用户失败，请检查参数是否有误！");
            }
            return ResponseJsonUtil.SUCCESS_WITH_NO_DATA;

        }else if(StringUtils.equals(identity,Identity.ADMIN)){
            Admin user = new Admin();

            try{
                adminService.save(user);
            }catch (Exception e){
                logger.info("新建admin错误,请检查参数"+param.toString());
                return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.ADD_USER_ERROR,"新建用户失败，请检查参数是否有误！");
            }
            return ResponseJsonUtil.SUCCESS_WITH_NO_DATA;

        }else{
            return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.IDENTITY_NON_EXISTENT,"该身份不存在");
        }
    }

    /**
     * 获取HR信息
     * @return
     */
    @PostMapping(value = "/admin/getHRInfo")
    @ResponseBody
    public ResponseJson getHRInfo(@RequestBody JSONObject param){
        Long userId = param.getLong("userId");
        if (userId == null){
            return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.MISSING_PARAMETERS,"缺少userId参数");
        }
        else{
            HR result = hrService.findByUserId(userId);
            return ResponseJsonUtil.getSuccessResult(result);
        }
    }
    /**
     * 修改HR信息
     * @return
     */
    @PostMapping(value = "/admin/changeHRInfo")
    @ResponseBody
    public ResponseJson changeHRInfo(@RequestBody JSONObject param){
        Long userId = param.getLong("userId");
        if (userId == null){
            return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.MISSING_PARAMETERS,"缺少userId参数");
        }
        else{
            HR hr = hrService.findByUserId(userId);

            if (hr == null){
                return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.USER_NON_EXISTENT,"用户不存在");
            }

            //将param的值附给hr
            for (String fieldName : param.keySet()){
                if (!Tools.setFieldValueByFieldName(fieldName,hr,param.getObj(fieldName))){
                    return ResponseJsonUtil.getErrorResult(ResponseStatusCodes.NOT_LOGGED_IN,"参数"+fieldName+"有误！！！");
                }
            }
            //持久化hr信息
            hrService.save(hr);

            Info result = new Info();
            result.setAddress(hr.getAddress());
            result.setBirthday(hr.getBirthday());
            result.setDepartment(hr.getDepartment());
            result.setEmail(hr.getEmail());
            result.setLevel(hr.getLevel());
            result.setPicture(hr.getPicture());
            result.setQuarters(hr.getQuarters());
            result.setUserId(hr.getUserId());
            result.setTelephone(hr.getTelephone());
            result.setUserName(hr.getUserName());
            return ResponseJsonUtil.getSuccessResult(result);
        }
    }
}
